<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/4/11
 * Time: 15:10
 */

namespace Biz\model;

use Doraemon\tools\ImgUrl;
use Biz\model\ShopSpecialGoods as mShopSpecialGoods;

class ShopSpecial extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'shop_special';

    const _SUB_TABLE = false;

    // 状态为正常
    const STATUS_NORMAL = 1;
    // 状态为下架
    const STATUS_OFFLINE = 2;

    // 状态为被删除
    const STATUS_DELETE = 9;

    //活动已结束
    const STATUS_END = 3;


    const TYPE_SPECIAL_GOODS = 1;
    const TYPE_SPECIAL_ACTIVITY = 2;
    const TYPE_SPECIAL_REGISTER = 3;

    public static $statusDesc = [
        self::STATUS_NORMAL => '正常',
        self::STATUS_OFFLINE => '下架',
        self::STATUS_DELETE => '删除',
        self::STATUS_END => '已结束'
    ];

    public static $activityType = [
        self::TYPE_SPECIAL_GOODS => '商品专题',
        self::TYPE_SPECIAL_ACTIVITY => '商城活动',
        self::TYPE_SPECIAL_REGISTER => '变价活动',
    ];

    const SPECIAL_SMALL = 0;
    const SPECIAL_LARGE = 1;


    public static function addSpecial($data)
    {
        $data['status'] = self::STATUS_NORMAL;
        $data['addtime'] = date("Y-m-d H:i:s");
        if (self::insert($data)->rowcount()) {
            return self::id();
        }

        return false;
    }

    public static function updateSpecialInfoById($id, $data)
    {
        $data['edittime'] = date("Y-m-d H:i:s");
        if (self::update($data, ["id" => $id])->rowcount()) {
            return $id;
        }
        return false;
    }

    public static function deleSpecialById($id)
    {
        if (self::update(['status' => self::STATUS_DELETE], ["id" => $id])->rowcount()) {

            return $id;
        }
    }

    public static function getSpecialInfoById($id, $type, $field = "*")
    {
        return self::get($field, [
                'id' => $id,
                'status' => self::STATUS_NORMAL,
                'special_type' => $type
            ]
        );
    }

    public static function getSpecialList($where = [], $order = [], $limit)
    {
        $params = [
            'AND' => $where,
            'ORDER' => $order ? $order : ['sort' => 'DESC'],
            'LIMIT' => $limit,
        ];

        $result = self::select('*', $params);
        $list = [];
        foreach ($result as $info) {
            self::formatInfo($info);
            $list[$info['id']] = $info;
        }

        return $list;
    }

    public static function getSpecialListCount($where)
    {
        return self::count('*', $where);
    }

    public static function getSpecials($type, $isLarge, $time, $field = '*')
    {


        $result = self::select($field, [
            'AND' => [
                'status' => self::STATUS_NORMAL,
                'is_large_special' => $isLarge,
                'start_time[<=]' => $time,
                'end_time[>=]' => $time,
                'special_type' => $type
            ],
            'ORDER' => ['sort' => 'DESC']
        ]);

        return $result;
    }

    public static function checkSort($sort, $specialId = '')
    {

        if (!empty($specialId)) {
            $where['AND']['id[!]'] = $specialId;
        }
        $where['AND']['sort'] = $sort;
        $where['AND']['status'] = self::STATUS_NORMAL;

        return self::select('sort', $where);
    }

    public static function getSpecialCount($where = [])
    {
        $params = [
            'AND' => $where,
        ];

        return self::count('*', $params);
    }


    public static function getSpecialPage()
    {

        return self::select('id', [
            'AND' => [
                'status' => self::STATUS_NORMAL,
                'special_type' => self::TYPE_SPECIAL_GOODS
            ],
            'ORDER' => ['sort' => 'DESC'],
        ]);
    }

    public static function specialList($time, $specialType = null, $field = "*", $order = ['small_sort' => 'DESC'], $limit = [])
    {
        $where = [
            'status' => self::STATUS_NORMAL,
            'start_time[<=]' => $time,
            'end_time[>=]' => $time,
        ];
        if (!is_null($specialType)) {
            $where['special_type'] = $specialType;
        }
        $params = [
            'AND' => $where,
            'ORDER' => $order,
        ];
        if ($limit) {
            $params['LIMIT'] = $limit;
        }
        return self::select($field, $params);
    }

    public static function getInfoById($id)
    {
        $info = self::get("*", ['id' => $id]);
        if($info) {
            self::formatInfo($info);
        }
        return $info;
    }

    public static function getSpecialInfo($specialId, $field = "*")
    {
        return self::get($field, [
            'AND' => [
                'id' => $specialId,
                'status' => self::STATUS_NORMAL,
                //'start_time[<=]' => date('Y-m-d H:i:s'), 未开始的活动可以预览
            ],
        ]);
    }

    public static function getActivityList($field = '*')
    {
        return self::select($field, [
            'AND' => [
                'status' => self::STATUS_NORMAL,
                'end_time[>]' => date('Y-m-d H:i:s'),
                'special_type' => self::TYPE_SPECIAL_REGISTER
            ],
            'ORDER' => ['sort' => 'DESC'],
        ]);
    }

    private static function formatInfo(&$info)
    {
        foreach ($info as $key => $value) {
            switch ($key) {
                case 'special_type':
                    $info['special_type_desc'] = self::$activityType[$value];
                    break;
                case 'status':
                    $info['status_desc'] = isset(self::$statusDesc[$value]) ? self::$statusDesc[$value] : '';
                    break;
                case 'share_img':
                    $info['share_img_url'] = $value ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $value,
                        ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
                    break;
                case 'special_info_img':
                    $info['special_info_img_url'] = $value ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $value, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                    break;
                case 'special_icon':
                    $info['special_icon_url'] = $value ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $value, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
                    break;
                case 'special_banner':
                    $info['special_banner_url'] = $value ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $value, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
            }
        }
        $info['status_desc'] = $info['end_time'] < date('Y-m-d H:i:s') ? self::$statusDesc[self::STATUS_END] : $info['status_desc'];
    }

    public static function getInfosBySpcialIdsAndType($specialIds, $specialType, $time = null, $field = '*')
    {
        $param['AND'] = [
            'id' => $specialIds,
            'special_type' => $specialType,
            'status' => self::STATUS_NORMAL
        ];
        if (!is_null($time) && $time) {
            $param['AND']['end_time[>=]'] = $time;
        }
        return self::select($field, $param);
    }

    public static function getWeekPurchaseList($where)
    {
        $list = [];
        $defaultWhere = [
            'status' => self::STATUS_NORMAL,
            'special_type' => self::TYPE_SPECIAL_REGISTER,
        ];
        $where['AND'] = array_merge($where['AND'], $defaultWhere);

        $result = self::select('*', [
            'AND' => $where['AND'],
            'LIMIT' => $where['LIMIT'],
            'ORDER' => $where['ORDER']
        ]);

        foreach ($result as $info) {
            self::formatInfo($info);
            $list[$info['id']] = $info;
        }

        return ['list' => $list, 'total' =>self::count('*', $where['AND'])];
    }
}